<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="shortcut icon" href="../images/logo-mi2.png" type="image/x-icon">
    <link rel="stylesheet" href="../css/cart.css">
    <script src="../js/jquery-3.6.0.min.js"></script>
    <script src="../js/cookie.js"></script>
    <script src="../js/interface.js"></script>
</head>

<body>
    <div class="cart-header">
        <div class="container">
            <div class="header-logo">
                <a href="./index.html" title="假小米官网"><img src="../images/logo-mi2.png" alt=""></a>
            </div>
            <div class="header-title">
                <h2>我的购物车</h2>
                <p></p>
            </div>
            <div class="site-topbar">
                <a href="./login.html">登录</a>
                <span>|</span>
                <a href="javascript:;">注册</a>
            </div>
        </div>
    </div>

    <!-- -------- -->
    <!-- -------- -->
    <!-- -------- -->

    <div class="mi-cart">
        <div class="container">
            <div class="cart-container">
                <div class="container-main">

                    <table id="cartTable">
                        <thead>
                            <tr class="cl">
                                <th class="col col-check check-all-box">
                                    <label>
                                        <input class="check-all check" type="checkbox" />
                                        &nbsp;&nbsp;全选
                                    </label>
                                </th>
                                <th class="col col-img">&nbsp;</th>
                                <th class="col col-name">商品名称</th>
                                <th class="col col-price">单价</th>
                                <th class="col col-num">数量</th>
                                <th class="col col-total">小计</th>
                                <th class="col col-action">操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <!-- <tr class="cl">
                                <td class="checkbox col col-check"><input class="check-one check" type="checkbox" />
                                </td>
                                <td class="goods col col-img">
                                    <img src="../images/videos_1.jpg" alt="" />
                                </td>
                                <td class="col col-name">Casio/卡西欧EX-TR350</td>
                                <td class="price col col-price">5999.88</td>
                                <td class="count col col-num">
                                    <span class="reduce"></span>
                                    <input class="count-input" type="text" value="1" />
                                    <span class="add">+</span>
                                </td>
                                <td class="subtotal col col-total">5999.88</td>
                                <td class="operation col col-action"><span class="delete">删除</span></td>
                            </tr>
                            <tr class="cl">
                                <td class="checkbox col col-check"><input class="check-one check" type="checkbox" />
                                </td>
                                <td class="goods col col-img">
                                    <img src="../images/videos_1.jpg" alt="" />
                                </td>
                                <td class="col col-name">Casio/卡西欧EX-TR350</td>
                                <td class="price col col-price">5999.88</td>
                                <td class="count col col-num">
                                    <span class="reduce"></span>
                                    <input class="count-input" type="text" value="1" />
                                    <span class="add">+</span>
                                </td>
                                <td class="subtotal col col-total">5999.88</td>
                                <td class="operation col col-action"><span class="delete">删除</span></td>
                            </tr>
                            <tr class="cl">
                                <td class="checkbox col col-check"><input class="check-one check" type="checkbox" />
                                </td>
                                <td class="goods col col-img">
                                    <img src="../images/videos_1.jpg" alt="" />
                                </td>
                                <td class="col col-name">Casio/卡西欧EX-TR350</td>
                                <td class="price col col-price">5999.88</td>
                                <td class="count col col-num">
                                    <span class="reduce"></span>
                                    <input class="count-input" type="text" value="1" />
                                    <span class="add">+</span>
                                </td>
                                <td class="subtotal col col-total">5999.88</td>
                                <td class="operation col col-action"><span class="delete">删除</span></td>
                            </tr> -->
                        </tbody>
                    </table>
                    <div class="foot cl" id="foot">
                        <a class="fl" id="deleteAll" href="javascript:;">删除</a>
                        <div class="fr selected" id="selected">
                            共<span id="allNum">3</span>件商品,已选择<span id="selectedTotal">0</span>件
                        </div>

                        <div class="fr closing" onclick="getTotal();">去结算</div>
                        <div class="fr total">
                            合计:<span id="priceTotal">0.00</span>元
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- -------- -->
    <!-- -------- -->
    <!-- -------- -->
    <div class="footer"></div>
</body>
<script>
    $(document).ready(function () {
        $(".footer").load("../html/footer.html")
    })


    $(async function () {
        var user = getCookie("lgc");
        if (!user) {
            location.href = "./login.html?returnUrl=" + encodeURIComponent(location.href);
        } else {
            $(".site-topbar").html(`欢迎您,${user} <button onclick="exit()">退出</button>`);
        }

        var result = await searchShoppingCarByUser({ user });  //await 异步改同步
        console.log(result);
        var { status, list } = result;

        if (status) {
            var html = "";
            list.forEach(({ id, goodsId, goodsName, goodsPrice, goodsImg, buyNum, subtotal, isChecked }) => {
                html += `<tr class="cl" data-id="${id}">
                                <td class="checkbox col col-check">
                                    <input class="check-one check" ${isChecked ? "checked" : ""} type="checkbox" />
                                </td>
                                <td class="goods col col-img">
                                    <img src="${goodsImg}" alt="" />
                                </td>
                                <td class="col col-name">${goodsName}</td>
                                <td class="price col col-price">${goodsPrice}</td>
                                <td class="count col col-num">
                                    <span class="reduce">${buyNum > 1 ? "-" : ""}</span>
                                    <input class="count-input" type="text" value="${buyNum}" />
                                    <span class="add">+</span>
                                </td>
                                <td class="subtotal col col-total">${subtotal}</td>
                                <td class="operation col col-action"><span class="delete">删除</span></td>
                            </tr>`
            })
            $("tbody").html(html)
        }

        isAllChecked();
        getTotal();
        isHasGoods();

        $(".check-all").click(async function () {
            // var status = this.checked;
            var status = $(this).prop("checked"); //状态 true:false

            var list = $(".check-one").parents("tr").map(function () {
                return $(this).attr("data-id");
            }).get();
            for (let i = 0; i < list.length; i++) {
                let id = list[i];
                console.log(status, id);
                var result = await updateGoodsChecked({ type: status * 1, id })
                var { status: flag, msg } = result;
                if (!flag) throw msg;
            }

            // var id = $(this).parents("tr").attr("data-id");
            // var result =  await updateGoodsChecked({type:status*1,id})
            // var {status,msg} = result;
            // if(!result) throw msg;
            $(".check-one").prop("checked", status);
            getTotal();
        })

        $(".check-one").click(async function () {
            // var flag = true;
            // $(".check-one").each(function(){
            //     if(!$(this).prop("checked")){
            //         flag = false;
            //     }
            // })
            // $(".check-all").prop("checked",flag);
            var status = $(this).prop("checked");  //状态 true:false
            var id = $(this).parents("tr").attr("data-id");
            var result = await updateGoodsChecked({ type: status * 1, id })
            var { status, msg } = result;
            if (!status) throw msg;

            isAllChecked();
            getTotal();

        })

        $(".add").click(async function () {
            var id = $(this).parents("tr").attr("data-id");
            var result = await addGoods({ id });
            var { status, msg } = result;
            if (!status) throw msg;

            var num = $(this).prev().val();
            num++;
            $(this).prev().val(num);

            var price = $(this).parent().prev().text() * 1;
            var subtotal = (num * price).toFixed(2);
            $(this).parent().next().text(subtotal)

            $(this).prev().prev().text("-");
            getTotal();
        })

        $(".reduce").click(async function () {
            var id = $(this).parents("tr").attr("data-id");
            var result = await reduceGoods({ id });
            var { status, msg } = result;
            if (!status) throw msg;


            var num = $(this).next().val();
            if (num == 1) return false;
            num--;
            if (num == 1) $(this).text("");
            $(this).next().val(num);

            var price = $(this).parent().prev().text() * 1;
            var subtotal = (num * price).toFixed(2);
            $(this).parent().next().text(subtotal)
            getTotal();
        })

        $(".delete").click(async function () {
            if (confirm("是否删除该数据?")) {
                var id = $(this).parents("tr").attr("data-id");
                var result = await delGoods({ ids: id });
                var { status, msg } = result;
                if (!status) throw msg;

                $(this).parents("tr").remove();
                isAllChecked();
                getTotal();
                isHasGoods();
            }
        })

        $("#deleteAll").click(async function () {
            if ($(".check-one:checked").length > 0) {
                if (confirm("是否删除选中的商品?")) {
                    var list = $(".check-one:checked").parents("tr").map(function () {
                        return $(this).attr("data-id")
                    }).get();
                    console.log(list);

                    var result = await delGoods({ ids: list.join(",") });
                    var { status, msg } = result;
                    if (!status) throw msg;

                    $(".check-one:checked").parents("tr").remove();
                    isAllChecked();
                    getTotal();
                    isHasGoods();
                }
            } else {
                alert("您还未选中任何商品!")
            }
        })

    })

    function isHasGoods() {
        if ($(".check-one").length <= 0) {
            $(".container-main").html(`<div class="empty-cart-wrap">
                        <div class="empty-cart-top">
                            <h2 class="login-tip">您的购物车还是空的！</h2>
                            <p class="login-desc">登录后将显示您之前加入的商品</p>
                            <a href="./index.html" class="btn-primary btn-login">马上去购物</a>
                        </div>
                    </div>`)
        }
    }

    function isAllChecked() {
        if ($(".check-one").length && $(".check-one:checked").length == $(".check-one").length) {
            $(".check-all").prop("checked", true);
        } else {
            $(".check-all").prop("checked", false);
        }
    }


    function getTotal() {
        var sum = 0;
        var allPrice = 0;
        var allNum = 0;
        $(".check-one").each(function () {
            allNum++;
        })
        $(".check-one:checked").each(function () {
            var num = $(this).parents("tr").find(".count-input").val() * 1;
            var subtotal = $(this).parents("tr").find(".subtotal").text() * 1;

            sum += num;
            allPrice += subtotal;
        })
        $("#allNum").text(allNum);
        $("#selectedTotal").text(sum);
        $("#priceTotal").text(allPrice.toFixed(2));

    }

    function exit() {
        delCookie("lgc");
        location.reload();
    }
</script>

</html>